package com.example.doublepink.dialogautodismisstest;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {
    private Button button;
    private long mLeftedTime;
    private AlertDialog.Builder builder;

    private Handler mCountDownHandler = new Handler();

    private Runnable mCountDownRunnable;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button = (Button) findViewById(R.id.btn);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                final SimpleDialog dialog = new SimpleDialog(MainActivity.this);
                dialog.setOnButtonClickListener(new SimpleDialog.OnButtonClickListener() {

                    @Override
                    public void onPositiveButtonClick() {

                        Intent intent = new Intent();
                        intent.setClass(MainActivity.this, SecondActivity.class);
                        startActivity(intent);
                        dialog.dismiss();
                    }

                    @Override
                    public void onNegativeButtonClick() {
                        dialog.dismiss();

                    }
                });
                dialog.show();

                doCountDown(dialog);
            }
        });

    }

    /**
     * 倒计时
     */
    private void doCountDown(final DialogInterface dialog) {
        mLeftedTime = 3 * 1000;
        mCountDownHandler.removeCallbacks(mCountDownRunnable);
        mCountDownHandler.postDelayed(mCountDownRunnable = new Runnable() {
            @Override
            public void run() {
                mLeftedTime -= 1000;
                if (mLeftedTime > 0) {
                    mCountDownHandler.postDelayed(this, 1000);
                } else {
                    mCountDownHandler.removeCallbacks(mCountDownRunnable);
                    dialog.dismiss();
                }
            }
        }, 1000);
    }


}
